//
//  SitRepTableViewController.m
//  Tazama NGO
//
//  Created by jsheriff on 3/4/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "SitRepTableViewController.h"
#import "FieldObservationDB.h"
#import "FieldObservationViewController.h"
#import "FieldObservationEditViewController.h"
#import "Notifications.h"
#import	"MenuTableViewController.h"
#import "MTLocationManager.h"
#import "KmlElementDB.h"
#import "MTWebServiceRequest.h"
#import "Settings.h"

@interface SitRepTableViewController ()

- (void)displayMessageDetail:(NSNotification *)notification;
- (void)webServiceRequestCompletedWithSuccess:(NSNotification *)notification;
- (void)webServiceRequestCompletedWithError:(NSNotification *)notification;
- (void)webServiceRequestRetryPending:(NSNotification *)notification;
- (void)readKmlFeedNow;

@end

#define kFieldObservationLabel @"Field Observation"

@implementation SitRepTableViewController

- (void)viewDidLoad {	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayMessageDetail:) name:kDisplayMessageDetail object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webServiceRequestCompletedWithSuccess:) name:kWebServiceRequestCompletedWithSuccess object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webServiceRequestCompletedWithError:) name:kWebServiceRequestCompletedWithError object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webServiceRequestRetryPending:) name:kWebServiceRequestRetryPending object:nil];
}	

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	FieldObservationDB *db = [FieldObservationDB sharedInstance];
    return [db.fieldObservationList count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	// exactly 6 cells (plus navigation bar and tab bar) displayed at one time
	return 61;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"SitRepTableViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	FieldObservationDB *db = [FieldObservationDB sharedInstance];
	FieldObservation *fo = [db.fieldObservationList objectAtIndex:indexPath.row];
	
    cell.textLabel.text = fo.immediateNeeds;
	cell.detailTextLabel.text = fo.observationText;
	cell.imageView.image = [UIImage imageNamed:@"caution40.png"];
    if (fo.messageSent) {
        [cell.imageView setAlpha:1.0];
    }
    else {
        [cell.imageView setAlpha:0.5];
    }
    
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	FieldObservationViewController *viewController = [[FieldObservationViewController alloc] initWithStyle:UITableViewStyleGrouped];

	FieldObservationDB *db = [FieldObservationDB sharedInstance];
	viewController.fieldObservation = [db.fieldObservationList objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

-(void)displayMessageDetail:(NSNotification *)notification {
	[self.navigationController popToRootViewControllerAnimated:NO];
	
	FieldObservationViewController *viewController = [[FieldObservationViewController alloc] initWithStyle:UITableViewStyleGrouped];
	
	viewController.fieldObservation = [notification.userInfo objectForKey:kFieldObservationKey];
	
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
	
	self.tabBarController.selectedIndex = 1;	
}

-(void)webServiceRequestCompletedWithSuccess:(NSNotification *)notification {
    MTWebServiceRequest* webServiceRequest = [notification.userInfo objectForKey:kWebServiceRequestKey];
    FieldObservation *fieldObservation = [[FieldObservationDB sharedInstance] getFieldObservationWithId:webServiceRequest.uuid];
    if (fieldObservation) {
        NSLog(@"SitRep Table View Controller notified of web service request success");
        fieldObservation.messageSent = YES;
        [self.tableView reloadData];
    
        // Read the KML after a delay (the delay is to allow the server time to get the new object into the KML feed)
        [self performSelector:@selector(readKmlFeedNow) withObject:nil afterDelay:10.0];
    }
}

- (void)webServiceRequestCompletedWithError:(NSNotification *)notification {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Comms Error" message:@"Unable to send field observation to server" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
    [alert show];
    [alert release];
}

- (void)webServiceRequestRetryPending:(NSNotification *)notification {
    
}

- (void)readKmlFeedNow {
    [[KmlElementDB sharedInstance] readFeedNow];
}

-(IBAction)tapAddButton:(id)sender {
    /*
    if (menuViewController == nil) {
        menuViewController = [[MenuTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    }
	menuViewController.menuItemList = [NSArray arrayWithObjects:kFieldObservationLabel, @"Situation Information", @"Casualty and Illness Summary", @"Response Resources Totals", @"Management Reporting Summary", nil];
	menuViewController.title = @"New Report Type";
    menuViewController.delegate = self;
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:menuViewController];
	
	[self.navigationController presentModalViewController:navigationController animated:YES];
    [navigationController release];
     */
    
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"New Report Type" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Field Observation", @"Situation Information", @"Casualty and Illness Summary", @"Response Resources Totals", @"Mgt Reporting Summary", nil];
//    [actionSheet showFromTabBar:self.tabBarController.tabBar];
//    [actionSheet release];
    
    FieldObservation *fieldObservation = [[FieldObservation alloc] init];
    fieldObservation.messageId = @"";
    fieldObservation.messageSent = NO;
    fieldObservation.immediateNeeds = @"";
    fieldObservation.severity = @"";
    fieldObservation.confidence = @"";
    fieldObservation.observationText= @"";
    CLLocation *currentLocation = MTLocationManager.sharedInstance.currentLocation;
    if (currentLocation) {
        fieldObservation.location = currentLocation.coordinate;
    }
    else {
        fieldObservation.location = CLLocationCoordinate2DMake(0.0, 0.0);
    }
    
    //            fieldObservation.location = CLLocationCoordinate2DMake(40.7553, 30.0698);
    
    fieldObservationEditViewController = [[FieldObservationEditViewController alloc] initWithStyle:UITableViewStyleGrouped];
    fieldObservationEditViewController.title = @"New Field Obsrvn";
    fieldObservationEditViewController.delegate = self;
    fieldObservationEditViewController.fieldObservation = fieldObservation;
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fieldObservationEditViewController];
    navigationController.navigationBar.barStyle = UIBarStyleType;
    
    [self.navigationController presentModalViewController:navigationController animated:YES];
    [navigationController release];

}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
        {
            FieldObservation *fieldObservation = [[FieldObservation alloc] init];
            fieldObservation.messageId = @"";
            fieldObservation.messageSent = NO;
            fieldObservation.immediateNeeds = @"";
            fieldObservation.severity = @"";
            fieldObservation.confidence = @"";
            fieldObservation.observationText= @"";
            CLLocation *currentLocation = MTLocationManager.sharedInstance.currentLocation;
            if (currentLocation) {
                fieldObservation.location = currentLocation.coordinate;
            }
            else {
                fieldObservation.location = CLLocationCoordinate2DMake(0.0, 0.0);
            }

//            fieldObservation.location = CLLocationCoordinate2DMake(40.7553, 30.0698);
            
            fieldObservationEditViewController = [[FieldObservationEditViewController alloc] initWithStyle:UITableViewStyleGrouped];
            fieldObservationEditViewController.title = @"New Field Obsrvn";
            fieldObservationEditViewController.delegate = self;
            fieldObservationEditViewController.fieldObservation = fieldObservation;
            
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fieldObservationEditViewController];
            
            [self.navigationController presentModalViewController:navigationController animated:YES];
            [navigationController release];
            break;
        }   
        default:
            break;
    }
}

-(void)didCancelFieldObservationEdit {
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

-(void)didSaveFieldObservationEdit {
    [self.navigationController dismissModalViewControllerAnimated:YES];
    FieldObservation * fieldObservation = fieldObservationEditViewController.fieldObservation;
    fieldObservation.uuid = CFUUIDCreate(kCFAllocatorDefault);
    FieldObservationDB *db = [FieldObservationDB sharedInstance];
    [db addNewFieldObservation:fieldObservation];

    [self.tableView reloadData];
}

/*
-(void)didChooseMenuItem {
    [self.navigationController dismissModalViewControllerAnimated:YES];

    if ([menuViewController.selectedMenuItem isEqualToString:kFieldObservationLabel] == YES) {
        FieldObservationEditViewController *viewController = [[FieldObservationEditViewController alloc] initWithStyle:UITableViewStyleGrouped];
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
        navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        [self.navigationController presentModalViewController:navigationController animated:YES];
        [navigationController release];
    }
}

-(void)didCancel {
    [self.navigationController dismissModalViewControllerAnimated:YES];    
}
*/
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[menuViewController release];

    [super dealloc];
}


@end

